package com.landtool.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.protobuf.InvalidProtocolBufferException;
import com.landtool.Netty.GlobalUtil;
import com.landtool.config.SysTemPropertyConfig;
import com.landtool.utils.ZipUtil;
import com.landtool.config.simulatedData;
import com.landtool.database.entity.BdDataFusion;
import com.landtool.database.entity.TgMidCountry;
import com.landtool.database.service.BdDataFusionService;
import com.landtool.utils.ZlibUtils;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.zeromq.ZMQ;

import javax.annotation.Resource;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Controller
public class Shipping {

    @Autowired
    private IndexerService indexerService;

    @Resource
    private BdDataFusionService bdDataFusionService;

    private static Logger log = LoggerFactory.getLogger(WebsocketServer.class);

    // 新的船只数据
    public static String strCurMB = "";
    public static JSONArray QianTaiarrMBList;// 排序id
    public static JSONArray HouTaiarrMBList;// 排序id
    public static Integer QianTaiSizeNum = 1500; // 分割数
    public static Integer HouTaiSizeNum = 10; // 分割数

    public static JSONArray updata = new JSONArray();
    public static JSONArray adddata = new JSONArray();
    public static JSONArray delectdata = new JSONArray();

    public static String cookie = "";
    public static Integer count = 0;
    public static HashMap <String, TgMidCountry> hmap;
    public static HashMap <String, BdDataFusion> RecentList;


    // 获取接口数据
    public String GetJson(String url) {
        String a = HttpUtil.get(url, 3000);
        return a;
    }

    public JSONArray getNewJSONArray(JSONArray array, String shipBelong) {
        JSONArray jsonArray = new JSONArray();
        for(int i=0;i<array.size();i++){
            JSONObject jsonObject = new JSONObject();
            JSONObject json = (JSONObject) array.get(i);
            Set<String> set = json.keySet();
            if(!set.contains("speed")){
                jsonObject.put("speed", 0);
            }

            Iterator<String> it = set.iterator();
            while (it.hasNext()) {
                String str = it.next();
                jsonObject.put(isAcronym(str), json.get(str));
            }

            //速度小于60节的才记录
            if (jsonObject.getDouble("speed") <= 60) {
                // 行政区划代码 广东的是44 海南的是46
                jsonObject.put("ship_belong", shipBelong);
                if (!set.contains("timestamp")) {
                    jsonObject.put("timestamp", DateUtil.now());
                }

                if (!set.contains("maxLength")) {
                    if (json.get("length") == null) {
                        jsonObject.put("maxLength", 0);
                    } else {
                        jsonObject.put("maxLength", json.get("length"));
                    }
                }

                if (!set.contains("type") || json.get("type") == null) {
                    jsonObject.put("ship_class", 1);
                }

                if (hmap != null && set.contains("mmsi") && !json.get("mmsi").toString().equals("0")) {
                    String mmsiKey = "";
                    try {
                        mmsiKey = json.get("mmsi").toString().substring(0, 3);
                    } catch (IndexOutOfBoundsException e) {
//                        log.error("错误mmsi:" + a.get("mmsi").toString());
                    }
                    if (hmap.containsKey(mmsiKey)) {
                        TgMidCountry tgMidCountry = hmap.get(mmsiKey);
                        jsonObject.put("Nationality", tgMidCountry.getEnName());
                    }
                }
                if (set.contains("mmsi") && json.get("mmsi").toString().equals("0")) {
                    jsonObject.remove("mmsi");
                }
                if (RecentList != null) {
                    Set<String> keySet = RecentList.keySet();
                    String target_id = shipBelong + jsonObject.getStr("target_id");
                    if (keySet.contains(target_id)) {
                        //先获取数据库对应的 光电最后时间
                        BdDataFusion bdDataFusion = RecentList.get(target_id);
                        long betweenDay = DateUtil.between(bdDataFusion.getTargetLasttime(), new DateTime(), DateUnit.HOUR);
                        if (betweenDay > 2) {
                            bdDataFusion.setDisable(1);
                            bdDataFusion.setTargetLasttime(new DateTime());
                            bdDataFusionService.update(bdDataFusion);
                        } else {
                            bdDataFusion.setTargetLasttime(new DateTime());
                            bdDataFusionService.update(bdDataFusion);
                            //将type改为6
                            jsonObject.put("ship_class", 6);
                        }
                    }
                }
                //增加时间停留字段
                jsonObject.put("duration", 0);
                jsonArray.add(jsonObject);
            }
        }
        return jsonArray;
    }


    public String isAcronym(String word) {
        if (word.equals("createTime")) {
            word = "timestamp";
        }
        if (word.equals("type")) {
            word = "ship_class";
        }
        if (word.equals("id")) {
            word = "target_id";
        }
        if (word.equals("name")) {
            word = "target_name";
        }
        if (word.equals("aisLength")) {
            word = "AisLength";
        }
        return word;
    }

    /**
     * 目标更新
     * @param oldList 旧数据
     * @param newList 新数据
     * @return
     */
    public JSONArray updata(JSONArray oldList, JSONArray newList) {
        JSONArray list3 = new JSONArray();
        int pointerB = 0;
        for (int i = 0; i < newList.size(); i++) {
            JSONObject newObj = (JSONObject) newList.get(i);
            for (int j = pointerB; j < oldList.size(); j++) {
                JSONObject oldObj = (JSONObject) oldList.get(j);
                if (oldObj.getInt("target_id") > (newObj.getInt("target_id"))) break;
                pointerB++;
                if (oldObj.getInt("target_id").equals(newObj.getInt("target_id"))) {
                    SetMMSI(newObj, oldObj);
                    if (!oldObj.get("timestamp").equals(newObj.get("timestamp")) && !oldObj.get("latitude").equals(newObj.get("latitude")) && !oldObj.get("longitude").equals(newObj.get("longitude"))) {
                        newObj.put("maxLength", Math.max(oldObj.getDouble("maxLength"), newObj.getDouble("maxLength")));

                        //计算时间差
                        timeDifference(newObj, oldObj);
                        list3.add(newObj);
                        break;
                    }
                }
            }
        }
        return list3;
    }


    public void timeDifference(JSONObject newObj, JSONObject oldObj) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date newDate = format.parse(newObj.getStr("timestamp"));
            Date oldDate = format.parse(oldObj.getStr("timestamp"));
            newObj.put("duration", ((newDate.getTime() - oldDate.getTime()) / 1000 / 60.0) + oldObj.getDouble("duration"));

        } catch (ParseException e) {
            e.printStackTrace();
            log.error("时间差计算错误");
        }
    }

    private void SetMMSI(JSONObject newObj, JSONObject oldObj) {
        //雷达，aisa，aisb，融合
        if (newObj.containsKey("mmsi") && newObj.getInt("mmsi") == 0 && oldObj.getInt("type") != null) {
            if (oldObj.getInt("type") == 1) {
                newObj.remove("mmsi");
                newObj.put("type", 1);
                if (newObj.containsKey("AisLength")) {
                    newObj.remove("AisLength");
                }
            }
        }
        if (oldObj.containsKey("mmsi") && newObj.containsKey("mmsi")) {
            if (oldObj.getInt("mmsi") != 0 && newObj.getInt("mmsi") == 0) {
                newObj.put("mmsi", oldObj.getInt("mmsi"));
            }
        }
    }

    public JSONArray MaxLength(JSONArray oldList, JSONArray newList) {
        int pointerB = 0;
        for (int i = 0; i < newList.size(); i++) {
            JSONObject newObj = (JSONObject) newList.get(i);
            for (int j = pointerB; j < oldList.size(); j++) {
                JSONObject oldObj = (JSONObject) oldList.get(j);
                if (oldObj.getInt("target_id") > (newObj.getInt("target_id"))) break;
                pointerB++;
                if (oldObj.getInt("target_id").equals(newObj.getInt("target_id"))) {
                    SetMMSI(newObj, oldObj);
                    if (!oldObj.get("timestamp").equals(newObj.get("timestamp")) && !oldObj.get("latitude").equals(newObj.get("latitude")) && !oldObj.get("longitude").equals(newObj.get("longitude"))) {
                        newObj.put("maxLength", Math.max(oldObj.getDouble("maxLength"), newObj.getDouble("maxLength")));
                        timeDifference(newObj, oldObj);
                        break;
                    }
                }
            }
        }
        return newList;
    }



    /**
     * @param oldList
     * @param newList
     * @return
     */
    public JSONArray delectdata(JSONArray oldList, JSONArray newList) {
        JSONArray list3 = new JSONArray();
        int pointerB = 0;
        for (int i = 0; i < oldList.size(); i++) {
            JSONObject oldObj = (JSONObject) oldList.get(i);
            boolean bool = false;
            for (int j = pointerB; j < newList.size(); j++) {
                JSONObject newObj = (JSONObject) newList.get(j);
                if (oldObj.getInt("target_id").equals(newObj.getInt("target_id"))) {
                    SetMMSI(newObj, oldObj);
                    bool = true;
                    pointerB++;
                    oldObj.put("alarmset", "0");
//                    tcRepository.save(indexerService.getTargetChangesEntity(oldObj));
                    break;
                } else if (oldObj.getInt("target_id") < newObj.getInt("target_id")) {
                    break;
                }
            }
            if (!bool) {
                list3.add(oldObj);
            }
        }
        return list3;
    }

    /**
     * 新增船只数
     *
     * @param oldList
     * @param newList
     * @return
     */
    public JSONArray adddata(JSONArray oldList, JSONArray newList) {
        JSONArray list3 = new JSONArray();
        int pointerB = 0;
        for (int i = 0; i < newList.size(); i++) {
            JSONObject newObj = (JSONObject) newList.get(i);
            boolean bool = false;
            for (int j = pointerB; j < oldList.size(); j++) {
                JSONObject oldObj = (JSONObject) oldList.get(j);
                if (oldObj.getInt("target_id").equals(newObj.getInt("target_id"))) {
                    SetMMSI(newObj, oldObj);
                    bool = true;
                    pointerB++;
                    break;
                } else if (newObj.getInt("target_id") < oldObj.getInt("target_id")) {
                    break;
                }
            }
            if (!bool) {
                newObj.put("alarmset", "1");
//                tcRepository.save(indexerService.getTargetChangesEntity(newObj));
                list3.add(newObj);
            }
        }
        return list3;
    }

    public void GetTcpJson(SysTemPropertyConfig sys) {
        while (true) {
            try {
                GetTcpInfo(sys);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("socket有问题" + e.toString());
            }
        }
    }

    private void GetTcpInfo(SysTemPropertyConfig sys) throws InterruptedException {
        ZMQ.Socket socket = null;
        ZMQ.Context context = ZMQ.context(1);
        try {
            socket = context.socket(ZMQ.SUB);
            socket.connect(sys.getTargetInfoUrl());
            socket.setReceiveTimeOut(10 * 1000);
            String filter = "Targets";
            socket.subscribe(filter.getBytes());
            while (true) {
                String msg = "";
                byte[] recv = {};
                try {
                    msg = socket.recvStr(0).trim();
                    recv = socket.recv(0);
                    log.info("recv的长度为" + recv.length);
                    Protocol.Targets t = null;
                    try {
                        t = Protocol.Targets.parseFrom(ZlibUtils.decompress(recv));
                        assert t != null;
                        JSONArray ShipEntityArray = getObjects(t);
                        // 如果配置了虚拟数据
                        simulatedData(sys.getSimulatedData(), ShipEntityArray);
                        // 排序
                        ShipEntityArray.sort(Comparator.comparing(obj -> ((JSONObject) obj).getInt("target_id")));
                        // 处理keys之后的集合
                        JSONArray jsonArray = getNewJSONArray(ShipEntityArray, sys.getShipBelong());

                        analyzeShippingQianDuan(jsonArray, sys.getShipBelong(), sys.getInfoUrl(), "ZMQ");
                        if (count % sys.getPushNum() == 0) {
                            analyzeShippingTcp(jsonArray, sys.getShipBelong());
                            if (sys.getElasticsearch().getOpen().equals("true")) {
                                indexerService.bulkIndex(Shipping.strCurMB);
                            }
                        }
                    } catch (InvalidProtocolBufferException e) {
                        e.printStackTrace();
                        log.error("解压数据错误");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("接受数据为空或者超时" + e.toString());
                    throw e;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("socket有问题" + e.toString());
            throw e;

        } finally {
            socket.disconnect(sys.getTargetInfoUrl());
            socket.close();
            context.term();
        }

    }

    /**
     * 获取cookie
     *
     * @param loginUrl 登陆地址
     */
    public void GetCookie(String loginUrl) {
        try {
            HttpResponse res = HttpRequest.post(loginUrl).execute();
            JSONObject json = JSONUtil.parseObj(res.body());
            Integer code = json.getInt("code");
            //用户登陆成功
            if (code == 0) {
                cookie = res.headers().get("Set-Cookie").get(0);
                if (!cookie.contains("JSESSIONID") && res.headers().get("Set-Cookie").size() == 2) {
                    cookie = res.headers().get("Set-Cookie").get(1);
                }
            }
            if (code == -1) {
                log.info("用户已被登陆");
                cookie = "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 退出登录
     * @param url
     */
    public void LoginOut(String url) {
        url = url.split("\\?")[0];
        url = url.replace("login", "logout");
        HttpRequest.post(url).cookie(cookie).execute();
    }


    /**
     * 获取数据
     *
     * @param sys 自定义参数
     * @param num 推送间隔次数
     */
//    public static void GetJson(SysTemPropertyConfig sys, Integer num) {
//        //该用户已登录
//        if (cookie.equals("")) {
//            GetCookie(sys.getLoginUrl());
//        }else {
//            try {
//                HttpResponse res = HttpRequest.post(sys.getTargetInfoUrl()).cookie(cookie).timeout(10*1000).execute();
//                String msg1 = res.body();
//                JSONArray jsonArray = new JSONArray();
//                //如果cookie不能使用，.body会返回空
//                if(StringUtils.isEmptyOrWhitespace(msg1)){
//                    //退出登录 302
//                    LoginOut(sys.getLoginUrl());
//                    cookie="";
//                }else {
//                    try {
//                        jsonArray = JSONUtil.parseArray(msg1);
//                        GetRESTInfo(sys, jsonArray, num);
//                    }catch (Exception e) {
//                        e.printStackTrace();
//                        log.error("JSON解析出错："+msg1);
//                    }
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//                log.error("HttpRequest 请求出错："+ e.getMessage());
//            }
//        }
//    }


//    public static void GetRESTInfo(SysTemPropertyConfig sys, JSONArray ShippingData, Integer num) {
    public void GetRESTInfo(SysTemPropertyConfig sys, Integer num) {
         ;
        JSONObject json = JSONUtil.parseObj(GetJson(sys.getTargetInfoUrl()));
        JSONArray ShipEntityArray = JSONUtil.parseArray(json.get("data"));
//        JSONArray ShipEntityArray = ShippingData;
        // 如果配置了虚拟数据
        simulatedData(sys.getSimulatedData(), ShipEntityArray);
        // 排序
        ShipEntityArray.sort(Comparator.comparing(obj -> ((JSONObject) obj).getInt("id")));
        // 处理keys之后的集合
        JSONArray jsonArray = getNewJSONArray(ShipEntityArray, sys.getShipBelong());

        analyzeShippingQianDuan(jsonArray, sys.getShipBelong(), sys.getInfoUrl(), "REST");
        if (num % sys.getPushNum() == 0) {
            analyzeShippingTcp(jsonArray, sys.getShipBelong());
        }
    }

    private void simulatedData(simulatedData simulatedData, JSONArray shipEntityArray) {
        if (simulatedData.getOpen().equals("true")) {
            Date date = DateUtil.date();
            Date StartTime = DateUtil.parse(simulatedData.getStartTime());
            if (date.compareTo(StartTime) > 0) {
                Integer numberPoints = Integer.valueOf(simulatedData.getNumberPoints());
                JSONArray Points = JSONUtil.parseArray(simulatedData.getPoints());
                Integer PointNum = Points.size();
                // 四个点，只构成三条线段，所以循环三次
                Integer i = count / (numberPoints / (PointNum - 1));
                if (i <= PointNum - 1) {
                    JSONObject beginXY = (JSONObject) Points.get(i);
                    JSONObject endXY = (JSONObject) Points.get(i + 1);

                    Float beginX = beginXY.getFloat("latitude");
                    Float beginY = beginXY.getFloat("longitude");
                    Float endX = endXY.getFloat("latitude");
                    Float endY = endXY.getFloat("longitude");
                    // 斜率
                    Double k = (endY - beginY) * 1.0 / (endX - beginX);
                    // 增量间隔
                    Float interval = (endX - beginX) / (numberPoints / (PointNum - 1));
                    Float x = beginX + interval * count;
                    Float y = (float) (k * (x - beginX) + beginY);

                    ShipEntity shipEntity = new ShipEntity();
                    shipEntity.setLatitude(Double.valueOf(x));
                    shipEntity.setLongitude(Double.valueOf(y));
                    shipEntity.setMmsi(413831902);
                    shipEntity.setTarget_id((long) 999999999);
                    shipEntity.setTarget_name("MoNiShuJu");
                    shipEntity.setSpeed(2.888);
                    shipEntity.setLength(18);
                    shipEntity.setMaxLength(18);
                    shipEntity.setTimestamp(DateUtil.now());
                    shipEntity.setDirection(16.0);
                    shipEntity.setQuality(1.0);
                    shipEntity.setShip_class(1);
                    shipEntityArray.add(shipEntity);
                }
            }
        }
    }

    /**
     * 处理zmq的数据
     *
     * @param t
     * @return
     */
    private JSONArray getObjects(Protocol.Targets t) {
        DecimalFormat df = new DecimalFormat(".00");
        assert t != null;
        count++;
        log.info("第" + count + "次获取数据;--获取数据，总数为：" + t.getListList().size());
        JSONArray ShipEntityArray = new JSONArray();
        for (int j = 0; j < t.getListList().size(); j++) {
            Protocol.Target a = t.getListList().get(j);
            // if (a.getId() == 436) {
            // System.out.println(i);
            ShipEntity shipEntity = new ShipEntity();
            Integer type = 0;
            type = getType(a, type);
            shipEntity.setShip_class(type);
            shipEntity.setLength(a.getLength());
            shipEntity.setMaxLength(a.getLength());
            if (a.getMmsi() == 0) {
                shipEntity.setMmsi(null);
            } else {
                shipEntity.setMmsi(a.getMmsi());
            }
            shipEntity.setTarget_name(a.getName());
            shipEntity.setLatitude(a.getPosition().getLatitude() * 180 / Math.PI);
            shipEntity.setLongitude(a.getPosition().getLongitude() * 180 / Math.PI);
            shipEntity.setSpeed((double) a.getSpeed());
            shipEntity.setCourse(df.format(a.getCourse() * 180 / Math.PI));
            shipEntity.setDirection(Double.valueOf(df.format(a.getHeading() * 180 / Math.PI)));
            shipEntity.setTarget_id(a.getUid());
            shipEntity.setDisplayId(a.getId());
            // Bahamas,China,Hong Kong等
            shipEntity.setNationality(a.getExtInfoMap().get("Nationality"));
            // 船只类型，货船或者游船
            shipEntity.setShipType(a.getExtInfoMap().get("Ship Type"));
            shipEntity.setWide(a.getExtInfoMap().get("Wide"));
            shipEntity.setAISReceiver(a.getExtInfoMap().get("AIS receiver"));
            shipEntity.setAisLength(a.getExtInfoMap().get("Length"));
            shipEntity.setImo(a.getExtInfoMap().get("IMO"));
            shipEntity.setCallSign(a.getExtInfoMap().get("Call_Sign"));
            StringBuilder radarKeyNum = new StringBuilder();
            Integer num = 0;
            for (String key : a.getExtInfoMap().keySet()) {
                String value = a.getExtInfoMap().get(key);
                if (value.equals("radar")) {
                    num++;
                    radarKeyNum.append(getNumbers(key)).append(",");
                }
            }
            if (num > 0) {
                radarKeyNum = new StringBuilder(radarKeyNum.substring(0, radarKeyNum.length() - 1));
            }
            shipEntity.setRadarids(radarKeyNum.toString());
            shipEntity.setQuality((double) a.getQuality());
            shipEntity.setTimestamp(DateUtil.now());
            ShipEntityArray.add(shipEntity);
        } // for循环完毕
        return ShipEntityArray;
    }


    // 处理数据(每次推送的是全部的数据)
    public void analyzeShippingTcp(JSONArray jsonArray, String shipBelong) {
        if (HouTaiarrMBList == null) {
            HouTaiarrMBList = jsonArray;
        } else {
            // 对比，求出最大船长
            jsonArray = MaxLength(HouTaiarrMBList, jsonArray);
            HouTaiarrMBList = jsonArray;
        }
        // 计算推送的次数
        try {
            TuiSongHouTai(jsonArray, GlobalUtil.channels2);
        } catch (IOException e) {
            e.printStackTrace();
        }
//        write("C:\\Users\\Administrator\\Desktop\\123123\\全部数据" + ".json", jsonArray.toString());
    }

    private void TuiSongHouTai(JSONArray msg, ChannelGroup channelGroup) throws IOException {
        Integer num = 0;
        if ((msg.size() % HouTaiSizeNum) == 0) {
            num = msg.size() / HouTaiSizeNum; // 将操作数转化为int型数据
        } else {
            num = (msg.size() / HouTaiSizeNum) + 1; // 将操作数转化为int型数据
        }

        for (int i = 1; i < num + 1; i++) {
            JSONArray Array = new JSONArray();
            if (msg.size() > HouTaiSizeNum * i) {
                for (int j = HouTaiSizeNum * (i - 1); j < HouTaiSizeNum * i; j++) {
                    Array.add(msg.get(j));
                }
            } else {
                for (int j = HouTaiSizeNum * (i - 1); j < msg.size(); j++) {
                    Array.add(msg.get(j));
                }
            }
            String a = Array.toString();
            for (Channel channel : channelGroup) {
                channel.writeAndFlush(new TextWebSocketFrame(a));
            }
        }
        log.info("推送全部数据");
//        write("C:\\Users\\Administrator\\Desktop\\123123\\" + 123 + ".json",msg.toString() );
    }

    // 处理数据(第一次推送全部的数据，第二次推送，处理后更新删除修改的数据)
    public void analyzeShippingQianDuan(JSONArray jsonArray, String shipBelong, String infoUrl, String type) {
        String ts = "";

        //在这里获取数据，每次都要更新保证时间戳不同
        long startTime = System.currentTimeMillis();
        if (QianTaiarrMBList == null) {
            QianTaiarrMBList = jsonArray;
        } else {
            // 更新点数
            updata = updata(QianTaiarrMBList, jsonArray);
            // 增加
            adddata = adddata(QianTaiarrMBList, jsonArray);
            // 消失点数
            delectdata = delectdata(QianTaiarrMBList, jsonArray);
            QianTaiarrMBList = jsonArray;
            //在这里获取数据，每次都要更新保证时间戳不同
            strCurMB = jsonArray.toString();
        }
        long endTime = System.currentTimeMillis();
        if (updata == null || adddata == null || delectdata == null) {
            log.info("---对比数据耗时：" + (endTime - startTime) + "ms");
        } else {
            log.info("---对比数据耗时：" + (endTime - startTime) + "ms");
        }
        if (jsonArray.size() > 0) {
            ts = ((JSONObject) jsonArray.get(0)).get("timestamp").toString();
        }
        TuiSongQianDuan(ts, GlobalUtil.channels);
        HashMap <String, Object> paramMap = new HashMap <>();
        paramMap.put("provinceid", shipBelong);
        paramMap.put("requesttimestring", ts);
        paramMap.put("requestamount", QianTaiarrMBList.size());
        paramMap.put("updata", updata.size());
        paramMap.put("adddata", adddata.size());
        paramMap.put("delectdata", delectdata.size());
        paramMap.put("porttype", type);
        try {
            HttpUtil.post(infoUrl, paramMap, 3000);
        } catch (Exception e) {
            log.info("写入日志失败");
        }

    }

    private void TuiSongQianDuan(String ts, ChannelGroup channelGroup) {
        // 计算推送次数
        Integer num = 0;
        // 判断三个数组的长度，取最长的
        Integer a[] = {updata.size(), adddata.size(), delectdata.size()};
        Arrays.sort(a);
        if ((a[2] % QianTaiSizeNum) == 0) {
            num = a[2] / QianTaiSizeNum; // 将操作数转化为int型数据
        } else {
            num = (a[2] / QianTaiSizeNum) + 1; // 将操作数转化为int型数据
        }

        for (int i = 1; i < num + 1; i++) {
            JSONArray divideUpdata = new JSONArray();
            JSONArray divideAdd = new JSONArray();
            JSONArray divideDelect = new JSONArray();

            divideUpdata = DivideFour(divideUpdata, updata, i);
            divideAdd = DivideFour(divideAdd, adddata, i);
            divideDelect = DivideFour(divideDelect, delectdata, i);

            String info = "{'ts':'" + ts + "','update':" + JSON.toJSONString(divideUpdata.toList(ShipEntity.class), SerializerFeature.WriteMapNullValue) + ",'add':" + JSON.toJSONString(divideAdd.toList(ShipEntity.class), SerializerFeature.WriteMapNullValue) + ",'delete':" + JSON.toJSONString(divideDelect.toList(ShipEntity.class), SerializerFeature.WriteMapNullValue) + "}";
            String msg = ZipUtil.gzip(info);
            for (Channel channel : channelGroup) {
                channel.writeAndFlush(new TextWebSocketFrame(msg));
            }
            long endTime = System.currentTimeMillis();
        }
        log.info("推送结束");
    }

    private JSONArray DivideFour(JSONArray divideArray, JSONArray jsonArray, int num) {
        // 获取存起来的数据，分割
        if (jsonArray.size() > QianTaiSizeNum * num) {
            for (int j = QianTaiSizeNum * (num - 1); j < QianTaiSizeNum * num; j++) {
                divideArray.add(jsonArray.get(j));
            }
        } else {
            for (int j = QianTaiSizeNum * (num - 1); j < jsonArray.size(); j++) {
                divideArray.add(jsonArray.get(j));
            }
        }
        return divideArray;
    }

    private Integer getType(Protocol.Target a, Integer type) {
        if (a.getType().getRadar()) {
            type = 1;
        }
        if (a.getType().getAisA()) {
            type = 2;
        }
        if (a.getType().getAisB()) {
            type = 3;
        }
        if (a.getType().getRadar() && a.getType().getAisA()) {
            type = 4;
        }
        if (a.getType().getRadar() && a.getType().getAisA()) {
            type = 5;
        }
        return type;
    }

    public static void write(String fileName, String content) {
        FileWriter writer = null;
        try {
            writer = new FileWriter(fileName, false); // 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件,false表示覆盖的方式写入
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 截取数字 【读取字符串中第一个连续的字符串，不包含后面不连续的数字】
    public String getNumbers(String content) {
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(content);
        while (matcher.find()) {
            return matcher.group(0);
        }
        return "";
    }

    public String getGapTime(long time) {
        long hours = time / (1000 * 60 * 60);
        long minutes = (time - hours * (1000 * 60 * 60)) / (1000 * 60);
        String diffTime = "";
        if (minutes < 10) {
            diffTime = hours + ":0" + minutes;
        } else {
            diffTime = hours + ":" + minutes;
        }
        return diffTime;
    }

}
